/**
 * @module  首页
 * @author xiongsha
 * @date 2020-12-21 21:31:01
 */

import React, { useState, useRef, useEffect } from 'react';
import request from '@src/utils/request';
import { RouteComponentProps } from 'react-router';
import { TabBar } from 'antd-mobile';
import Home from './Home';
import OrderList from './components/OrderList';
import Mine from './components/Mine';
import Ewm from './components/Ewm';
import './index.less';

interface IMine {
  account?: string;
  avatar?: string;
  bound_phone?: boolean;
  bound_wechat?: boolean;
  created_at?: string;
  email?: string;
  email_verified_at?: string;
  id?: number;
  introduction?: string;
  local?: string;
  name?: string;
  nickname?: string;
  phone?: string;
  sex?: number;
  updated_at?: string;
}

const TabCom: React.FC<RouteComponentProps> = (props: RouteComponentProps) => {
  let homeName = (props.match.params as any).name;
  const [selectedTab, setSelectedTab] = useState('home');
  const [mine, setMine] = useState<IMine>({});
  const child = useRef<any>(null);
  const ewmChild = useRef<any>(null);

  const renderContent = (pageText) => {
    return (
      <div style={{ height: '100%', textAlign: 'center' }}>
        {pageText === '首页' ? (
          <Home></Home>
        ) : pageText === '订单' ? (
          <OrderList history={props.history} ref={child}></OrderList>
        ) : pageText === '会员码' ? (
          <Ewm mine={mine} ref={ewmChild}></Ewm>
        ) : (
          <Mine mine={mine}></Mine>
        )}
      </div>
    );
  };
  const getUser = (tab) => {
    request('get', '/api/v1/user').then((res) => {
      if (res && res.code === 200) {
        const { data } = res;
        if (!data.bound_phone) {
          props.history.replace('/login');
        }
        if (tab === 'order') {
          child.current!.changeVal();
        }
        if (tab === 'ewm') {
          ewmChild.current.getVal();
        }
        setMine(res.data);
      }
    });
  };

  const getCode = (tab) => {
    // 获取微信code
    // localStorage.setItem('openid', 'om4QP54F0KkmIZYHIfRiMj3t7JWM');
    const openid = localStorage.getItem('openid');
    const token = localStorage.getItem('token');
    if (openid && token) {
      // 如果有openid且有token
      getUser(tab);
      return;
    }
    let { search } = location;
    let seaechArr = search.split('&');
    seaechArr = seaechArr[0].split('=');
    const code = seaechArr[1];
    if (!openid && !code) {
      location.href =
        'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9f0af8e61b261be9&redirect_uri=http%3a%2f%2ftianrui.vic0922.top%2f&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
    }
    if (openid || code) {
      request('post', '/api/v1/socials/authorizations', {
        code: openid ? undefined : code,
        openid,
      }).then((res) => {
        if (res && res.code === 200) {
          localStorage.setItem('token', res.data.access_token);
          localStorage.setItem('openid', res.data.openid);
          localStorage.setItem('time', res.data.expiration);
          getUser(tab);
        }
      });
    }
  };

  const selectTab = (cur) => {
    // 选择tab
    setSelectedTab(cur);
    if (cur !== 'home') {
      getCode(cur);
    }
  };

  useEffect(() => {
    console.log(homeName, 'ho');
    if (homeName) {
      selectTab(homeName);
    }
  }, [homeName]);
  
  return (
    <div className="main">
      <TabBar
        className="main-bar"
        unselectedTintColor="#949494"
        tintColor="#33A3F4"
        barTintColor="white"
      >
        <TabBar.Item
          title="首页"
          key="home"
          icon={<img className="tab-icon" src={require('@src/img/icon-home.png')} alt="" />}
          selectedIcon={<img className="tab-icon" src={require('@src/img/home.png')} alt="" />}
          selected={selectedTab === 'home'}
          onPress={() => selectTab('home')}
          data-seed="logId0"
        >
          {renderContent('首页')}
        </TabBar.Item>
        <TabBar.Item
          icon={<img className="tab-icon" src={require('@src/img/icon-dingdan.png')} alt="" />}
          selectedIcon={<img className="tab-icon" src={require('@src/img/dingdan.png')} alt="" />}
          title="订单"
          selected={selectedTab === 'order'}
          onPress={() => selectTab('order')}
          key="order"
          data-seed="logId1"
        >
          {renderContent('订单')}
        </TabBar.Item>
        <TabBar.Item
          icon={<img className="tab-icon" src={require('@src/img/icon-ewm.png')} alt="" />}
          selectedIcon={<img className="tab-icon" src={require('@src/img/ewm.png')} alt="" />}
          title="会员码"
          selected={selectedTab === 'ewm'}
          onPress={() => selectTab('ewm')}
          key="ewm"
          data-seed="logId2"
        >
          {renderContent('会员码')}
        </TabBar.Item>
        <TabBar.Item
          icon={<img className="tab-icon" src={require('@src/img/icon-wode.png')} alt="" />}
          selectedIcon={<img className="tab-icon" src={require('@src/img/wode.png')} alt="" />}
          title="我的"
          key="mine"
          selected={selectedTab === 'mine'}
          onPress={() => selectTab('mine')}
          data-seed="logId3"
        >
          {renderContent('我的')}
        </TabBar.Item>
      </TabBar>
    </div>
  );
};

export default TabCom;
